package com.ch999.comparedata.hander;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.ch999.comparedata.entity.SQLUndoLog;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.insert.Insert;
import org.apache.ibatis.mapping.SqlCommandType;

import javax.sql.DataSource;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

public class InsertHander extends AbstractHandler{


    private Insert insert;
    private Object parameter;

    public InsertHander(Statement statement, DataSource dataSource,Object parameter, String dataSourceType) {
        super(statement, dataSource,dataSourceType);
        this.parameter = parameter;
        insert = (Insert) statement;
    }

    @Override
    public void preHandle() throws Throwable {

    }

    @Override
    public void postHandle() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        SQLUndoLog sqlUndoLog = new SQLUndoLog();
        sqlUndoLog.setSqlCommandType(SqlCommandType.INSERT);
        sqlUndoLog.setTableName(insert.getTable().getName());
        sqlUndoLog.setBeforeImage(null);
        Field[] fields = parameter.getClass().getDeclaredFields();
        Integer id =null;
        for (Field field:fields){
            if (field.toString().contains("static")){
                continue;
            }
            String name = field.getName();
            if ("id".equalsIgnoreCase(name)){
                name = name.substring(0,1).toUpperCase()+name.substring(1);
                Method m = parameter.getClass().getMethod("get"+name);
                id = (Integer) m.invoke(parameter);
                break;
            }
        }
        String resetSql = String.format(delSql,insert.getTable().getName(),id);
        try {
            String executeSql = String.format(getExecuteSql(dataSourceType),insert.getTable().getName(),"id = "+id);
            List<Entity> result = Db.use(dataSource).query(executeSql);
            sqlUndoLog.setAfterImage(result.get(0));
            //保存日志
            addUndoLog(sqlUndoLog,resetSql);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
